%this file turns the *B.mat (blink removed) data into the *C.mat (trial by trail analized) data 
%custom software by bcoe@biomed.queensu.ca
%
% eyelink2_saccade_detector_apr05
%

clear
%close all;
scnsize = get(0,'ScreenSize');


redraw=0;
find_all_sac=1;
find_tgt_sac=1;

files = dir('*B.mat'); % find all files with the B.mat extention
% data_list entries must be 8 characters long.(eyelink2 still lives in dos)
if length(files)==0
    disp(' ');
    disp('there are no *B.mat files in current directory');
    cd;
    return
end

for fp_num=1:length(files)
    file_name=files(fp_num).name
    load(file_name)
    if ~isfield(B,'t_state')% just for andrews old data
        B.t_state(1,:)=' ITI      ';  % duration of iti
        B.t_state(2,:)=' FIX      ';  % duration of fix WITHOUT checking eye
        B.t_state(3,:)=' GAP      ';  % random duration
        B.t_state(4,:)=' CUE_TGT  ';  % duration of cue&tgt WITHOUT checking eye
        B.t_state(5,:)=' BLACK    '; 
    end
    for i=1:size(B.t_state,1)
        % 		if sum(B.t_state(i,:)=='&')
        % 			B.t_state(i,find(B.t_state(i,:)=='&'))='_';
        % 			eval(['S_' B.t_state(i,2:end) '=' num2str(i) ';']);
        % 		else
        eval(['S_' B.t_state(i,2:end) '=' num2str(i) ';']);
        % 		end
        
    end
    c=B.colors;        
    if redraw;
        fig(31);
        set(31,'position',[1 31 scnsize(3)  scnsize(4)*.895],'name',file_name,'NumberTitle','off');
        clf;%cla;hold on;tickout            
    end
    tr_num=1;
    %	while tr_num<length(B.ang_ecc)+1
    while tr_num<length(B.timeb) % 21-april-2005
        B.iti(tr_num)=B.timeb(tr_num,S_ITI);
        B.fix_on(tr_num)=B.timeb(tr_num,S_FIX);
		if B.timeb(tr_num,S_GAP)
			B.fix_off(tr_num)=B.timeb(tr_num,S_GAP);
		else
			B.fix_off(tr_num)=B.timeb(tr_num,S_CUE_TGT);
		end
		B.cue_tgt_on(tr_num)=B.timeb(tr_num,S_CUE_TGT);
		B.cue_tgt_off(tr_num)=B.timeb(tr_num,S_BLACK);
		B.tr_end(tr_num)=B.timeb(tr_num+1,S_ITI);
		t_range=[B.iti(tr_num) B.tr_end(tr_num)];
		t_align=B.fix_on(tr_num);
		[val e_start]=min(abs(B.time-t_range(1)));
		[val e_end]  =min(abs(B.time-t_range(2)));
		[val e_fix_on]  =min(abs(B.time-B.fix_on(tr_num)));
		[val e_fix_off]  =min(abs(B.time-B.fix_off(tr_num)));
		[cnt val]=hist_b(round(B.eye_x(e_fix_on:e_fix_off)*10)/10);
		x_adj=minfix(val(cnt==max(cnt)));
        [cnt val]=hist_b(round(B.eye_y(e_fix_on:e_fix_off)*10)/10);
        y_adj=minfix(val(cnt==max(cnt)));
        B.x_adj(tr_num)=x_adj;
        B.y_adj(tr_num)=y_adj;
        clear cnt val
        B.e_start(tr_num)=e_start;
        B.e_end(tr_num)=e_end;
        
        eye_x=(B.eye_x(e_start:e_end)-x_adj);
        eye_x_raw=(B.eye_x_raw(e_start:e_end)-x_adj);
        eye_y=(B.eye_y(e_start:e_end)-y_adj);
        eye_y_raw=(B.eye_y_raw(e_start:e_end)-y_adj);
        time=B.time(e_start:e_end)-t_align;
        vel_x=B.vel_x(e_start:e_end);
        vel_y=B.vel_y(e_start:e_end);
        speed=B.speed(e_start:e_end);
        blink=B.blink(e_start:e_end);
        [tgt_x tgt_y]=polar2cart(B.ang_ecc(tr_num,:));
        if B.anti(tr_num)
            cuecolor=c.ANTI;
            t_title='ANTI';        
        else
            cuecolor=c.PRO;
            t_title='PRO';
        end        
        if redraw % part 1of2
            fig(31);            
            %%% position x&y plot
            h_pos_xy=subplot('Position',[0.05 0.73 0.93 0.25]);cla;axis auto;hold on;tickout;
            axis([min(time) max(time) -40 40 ]);
            vline([B.fix_on(tr_num) B.fix_off(tr_num)]-t_align,'k');
            vfill(B.cue_tgt_on(tr_num)-t_align, B.cue_tgt_off(tr_num)-t_align,cuecolor);
            vline(B.fix_off(tr_num)-t_align,'--k');
            hline(0,'k');
            plot(time,eye_x_raw,'c');
            plot(time,eye_y_raw,'m');
            plot(time(blink>4),eye_x_raw(blink>4),'.c');
            plot(time(blink>4),eye_y_raw(blink>4),'.m');
            plot(time,eye_x,'.-b');
            plot(time,eye_y,'.-r');
            plot(time(blink>4),eye_x(blink>4),'.','color',[.1 .1 .5]);
            plot(time(blink>4),eye_y(blink>4),'.','color',[.5 .1 .1]);
            %%% velocity x&y  & speed plot
            h_vel_xy=subplot('Position',[0.05 0.42 0.93 0.25]);cla;axis auto;hold on;tickout;xlim([min(time) max(time)])
            axis([min(time) max(time) -500 500 ]);
            vline([B.fix_on(tr_num) B.fix_off(tr_num)]-t_align,'k');  
            vfill(B.cue_tgt_on(tr_num)-t_align, B.cue_tgt_off(tr_num)-t_align,cuecolor);
            plot(time,vel_x,'.-','color',[.1 .1 .5]);
            plot(time,vel_y,'.-','color',[.5 .1 .1]);
            plot(time,speed,'.-g');
            plot(time(blink>4),speed(blink>4),'.','color',[.1 .6 .1]);
        end
        %%%%%%% find all saccades
        if find_all_sac            
            fix_noise=speed(speed<60); % most people use a fixed 50dps for saccade onset. here i remove all speeds over 60dps ... 
            sac_thres=max([20 mean(fix_noise)+(3*std(fix_noise))]); % and find the mean and 3std to create a variable threshold to compensate for different noise levels
            B.sac_thres(tr_num)=sac_thres;
            sac_pts=find(speed>(sac_thres)); % sometimes 50's too low and sometimes it's too high.
            sac_start_times=[];
            if length(sac_pts)>0
                sac_start_pos=(sac_pts(find(diff(sac_pts)>3)+1));
                sac_start_pos=[sac_pts(1); sac_start_pos];
                sac_end_pos=(sac_pts(find(diff(sac_pts)>3)));
                sac_end_pos=[sac_end_pos;sac_pts(end)];
                sac_start_times=time(sac_start_pos);
                sac_end_times=time(sac_end_pos);
                sac_dur=sac_end_times-sac_start_times; % make sure the 'saccades' last... 
                sac_start_pos(sac_dur<20)=[];% ignore if too short: <20 ms long
                sac_end_pos  (sac_dur<20)=[];% ignore if too short: <20 ms long
                clear sac_dur;
                sac_pts2=[];
                fast_enought=[];
                for i=1:length(sac_start_pos)
                    sac_pts2=[sac_pts2 sac_start_pos(i):sac_end_pos(i)];
                    fast_enought(i)=sum(speed(sac_start_pos(i):sac_end_pos(i))>50);
                end
                sac_start_pos(fast_enought==0)=[];% ignore if too slow: peak speed <=60 dps 
                sac_end_pos  (fast_enought==0)=[];% ignore if too slow: peak speed <=60 dps 
                
                sac_start_times=time(sac_start_pos);
                sac_end_times=time(sac_end_pos);
                
                if redraw % part 1of2
                    match_any(sac_pts2,find(blink>4));
                    plot(time(sac_pts2),speed(sac_pts2),'.','color',[.8 .8 .8]);
                    vline(sac_start_times);
                end
            end
            
        end % find all sac
        %%%%%%%%%%%%find post target saccade 
        B.srt(tr_num)=0;
        [val B.sac_on_loc(tr_num) ]=minfix(B.time-B.cue_tgt_on(tr_num));
        B.sac_off_loc(tr_num)=B.sac_on_loc(tr_num);
        tsac_range=[];
        if find_tgt_sac & length(sac_start_times)>0%find right saccade
            bad_sac=0;
            bad_sac(length(sac_start_times),1)=0;%create a fuzzy boolean
            bad_sac(sac_start_times<(B.cue_tgt_off(tr_num)-t_align+100))=1; % ditch if too early
            bad_sac(sac_start_times>(B.cue_tgt_off(tr_num)-t_align+1800))=1; % ditch if too late
            %bad_sac(abs_speed(find_any(temp_eye_time,(round((sac_end_times-sac_start_times)/2)+sac_start_times)))<120)=1; % ditch if too slow <120 dps
            if length(sac_start_pos)>1 % if multiple saccades
                bad_sac([abs(eye_x(sac_start_pos))>5 & abs(eye_y(sac_start_pos))>5 ])=1; % if the saccade starts with the eye 6 deg (x&y) away from the fix )
            end
            tsac_on_time =min(sac_start_times(find(~bad_sac))); %find first saccade that matches guidlines
            tsac_off_time=min(sac_end_times  (find(~bad_sac))); %find first saccade that matches guidlines
            tsac_on_pos  =min(sac_start_pos  (find(~bad_sac))); %find first saccade that matches guidlines
            tsac_off_pos =min(sac_end_pos    (find(~bad_sac))); %find first saccade that matches guidlines
            warning off MATLAB:colon:operandsNotRealScalar
            tsac_range=tsac_on_pos:tsac_off_pos;
            warning on  MATLAB:colon:operandsNotRealScalar
            if tsac_on_time
                B.srt(tr_num)=tsac_on_time-(B.cue_tgt_on(tr_num)-t_align);
                B.sac_on_loc(tr_num)=find(B.time==tsac_on_time+t_align);
                B.sac_off_loc(tr_num)=find(B.time==tsac_off_time+t_align);
            end
            % tgt_sac_pts=sac_pts(temp_eye_time(sac_pts)>=sac_start & temp_eye_time(sac_pts)<=sac_end);
            % sac_on_pos=min(tgt_sac_pts);
            % sac_on_time=temp_eye_time(sac_on_pos);
            % sac_off_pos=(min([max(tgt_sac_pts) min(tgt_sac_pts(find(diff(tgt_sac_pts)>3))) ] ) ); % find a break in saccade points that is longer than 3 millisoconds.
            % sac_off_time=temp_eye_time(sac_off_pos);
            % vline(sac_start_times,'-.g' );
            % vline(sac_end_times,'r' );
            % else
            % tsac_on_pos=sac_start_pos(sac_num);
            % tsac_off_pos=sac_end_pos(sac_num);
            % tsac_on_time=temp_eye_time(sac_on_pos);
            % tsac_off_time=temp_eye_time(sac_off_pos);
        end% find target saccade
        
        
        if redraw % part 2of2
            hline(sac_thres);
            plot(time(sac_pts2),speed(sac_pts2),'.','color',[.7 .7 .7]);
            %%% post target eye position plot
            h_sac_polar=subplot('Position',[0.7 0.042 0.20 0.28]);cla;hold on;tickout;axis square; axis([-30.5 30.5 -30.5 30.5])
            axis off;
            vline([-30 0 30],'k');
            hline([-30 0 30],'k');
            if length(tsac_range)>0
                plot(eye_x(tsac_range)-x_adj,eye_y(tsac_range)-y_adj,'.');
            end
            plot(0,0,'.k');
            plot(0,0,'ok');
            if B.peri(tr_num);
                tgt(1)=plot(tgt_x,tgt_y,'.','color',cuecolor,'markersize',18);            
            else
                tgt(1)=plot(tgt_x,tgt_y,'.','color',c.WHITE,'markersize',18);
                tgt(2)=plot(0,0,'.','color',cuecolor,'markersize',18);
            end
            if tsac_range
                temp_range=tsac_range(1):tsac_range(1)+(1000/mean(diff(time)));% show 1 second of eye data after saccade
            else
                temp_range=700:700+(1000/mean(diff(time)));% show 1 second of eye data after 700 ms
            end
            
            plot(eye_x(temp_range)-x_adj,eye_y(temp_range)-y_adj,'k');
            for i=1:10
                temp=find(speed(temp_range)>10*i);
                plot(eye_x(temp_range(temp))-x_adj,eye_y(temp_range(temp))-y_adj,'.','color',[0.1*i 0.1*i 1-(0.1*i ) ]);
            end
            title(t_title);
            
            
            h_sac_xy=subplot('Position',[0.057 0.075 0.60 0.25]);hold on;cla;
            axis([B.sac_on(tr_num)-B.cue_tgt_off(tr_num)-100 B.sac_on(tr_num)-B.cue_tgt_off(tr_num)+200 -20 20 ]);
            %if tr_num>1,delete([p_a p_b ]);end
            if tsac_range
                sac_on=time(min(tsac_range));
                vline(time(min(tsac_range))-(B.cue_tgt_off(tr_num)-t_align),cuecolor);
                vline( sac_on -(B.cue_tgt_off(tr_num)-t_align),cuecolor);
                vline(B.sac_on(tr_num)-B.cue_tgt_off(tr_num))
                vline(B.sac_off(tr_num)-B.cue_tgt_off(tr_num))
                
                [val loc1]=minfix(time-(B.cue_tgt_off(tr_num)-t_align));
                [val loc2]=minfix(time-(B.cue_tgt_off(tr_num)-t_align+1500));
                view_sac_range=loc1:loc2;
                p_a(1)=plot(time(view_sac_range)-(B.cue_tgt_off(tr_num)-t_align),eye_x(view_sac_range),'.-c','linewidth',2);
                p_b(1)=plot(time(view_sac_range)-(B.cue_tgt_off(tr_num)-t_align),eye_y(view_sac_range),'.-m','linewidth',2);
                p_a(2)=plot(time(tsac_range)-(B.cue_tgt_off(tr_num)-t_align),eye_x(tsac_range),'.b','linewidth',2);
                p_b(2)=plot(time(tsac_range)-(B.cue_tgt_off(tr_num)-t_align),eye_y(tsac_range),'.r','linewidth',2);
                p_a(2)=plot(time(view_sac_range)-(B.cue_tgt_off(tr_num)-t_align),(speed(view_sac_range)/10)-20,'g','linewidth',2);
                hline((B.sac_thres(tr_num)/10)-20)
            else
                p_a=plot(0,0);
                p_b=plot(0,0);% for delete routine            
                sac_on=0;
            end
            
            [mouse_x,mouse_y,button] = ginput(1);
            uistate = uiunsuspend(gcf);% a sub function i touched up to reenable the zoom (and other) functions; 
        else
            button=0;
            tr_num=tr_num+1;
        end % if redraw
        
        % fig(30);hold on
        % xlim([-100 1200])
        % plot((B.cue_tgt_on(tr_num)-B.fix_off(tr_num)),sac_on-(B.cue_tgt_off(tr_num)-t_align),'.','color',cuecolor)
        % pause
        %
        % 
        switch button
            %  case 1, % left mouse button should select the saccade to be viewed 
            % if (sum(mouse_x<get(gca,'xlim'))==1 & sum(mouse_y<get(gca,'ylim'))==1) % in current plot's lim's
            %  switch gca % get current axis (built-in function) 
            %  case ap_eye_xy % upper right xy plot
            % %find nearest eyepos
            % diff_x=x-temp_eye_x;
            % diff_y=y-temp_eye_y;
            % abs_diff=sqrt(diff_x.^2+diff_y.^2);
            % [val pos]=min(abs_diff);
            % %degug stuff
            % %fig(2);hold on;axis auto;axis equal;
            % %cla;
            % %plot(temp_eye_x,temp_eye_y,'.');
            % %plot(x,y,'.r')
            % %plot(temp_eye_x(pos),temp_eye_y(pos),'or');
            % %plot(temp_eye_x(sac_start_pos),temp_eye_y(sac_start_pos),'og');    
            % %plot(temp_eye_x(sac_end_pos),temp_eye_y(sac_end_pos),'om');
            % %fig(1)
            % if sum((sac_start_pos<pos))~=sum((sac_end_pos<pos)),% in saccade
            %  sac_num=max(find(sac_start_pos<pos));
            %  redraw=1;
            %  find_tgt_sac=0; 
            %  find_all_sac=0;
            % end
            % 
            %  case ap_saccade, %lower right
            % %do nothing for now
            %  case ap_xy_speed %upperleft
            % if (sum(sac_start_times<x)~=sum(sac_end_times<x)) % during a saccade only
            %  sac_num=max(find(sac_start_times<x));
            %  redraw=1;
            %  find_tgt_sac=0; 
            %  find_all_sac=0;
            % end %times
            %  end % switch gca
            % end % if in plot lim's
            % 
            case 27, 
                set(31,'position',[scnsize(3)/3 scnsize(4)/3 scnsize(3)/3 scnsize(4)/3])
                return;      
            case 66 % B for previous file
                %file=max([1 file-1]);
                tr_num=1000; %over flow
            case 78 % N for next file
                %file=file+1;    
                tr_num=1000; %over flow
            case 107 % k
                %run with no pauses
                redraw=0;
                uimenufcn(gcf,'WindowCommandWindow');
                close all;
            case 112, % p for pause
                pause; 
                %  case 103, % g for goto
                % pause(0.01); % prevents flickering between windows
                % clc; 
                % %how do i send command window to the front? you'd thing input would do this automatically, right!
                % uimenufcn(gcf,'WindowCommandWindow');
                % a=input(['\n\n\nGoTo Trial Number(1:' num2str(length(T.start)) '): ' ],'s');
                % fig(1);
                % clc;
                % if str2num(a) 
                %  if str2num(a)>1 & str2num(a)<=length(B.ang_ecc)
                % tr_num=str2num(a); 
                % redraw=1;
                % find_tgt_sac=1; 
                % find_all_sac=1;
                %  end
                % end
            case 110, % n for next
                tr_num=tr_num+1; 
                redraw=1;
                find_tgt_sac=1; 
                find_all_sac=1;
            case 98, % b for back
                tr_num=max([1 tr_num-1]);
                redraw=1;
                find_tgt_sac=1; 
                find_all_sac=1;
%             otherwise % loop around but don't waist time redrawing
%                 find_tgt_sac=1;
%                 find_all_sac=1;
        end % switch button
        
    end % trial
    C=B;
    if redraw
		clc;
        uimenufcn(gcf,'WindowCommandWindow');
        yn=input(['save file ' C.name 'C.mat?'],'s');
        while floor(mean(yn(1)~=['y' 'n']))
            clc;
            yn=input(['save file ' C.name 'C.mat?'],'s');
        end
        if yn=='y'    
            save([C.name 'C.mat'], 'C')  
            disp(['saved file name ' C.name 'C.mat']);
        end
    else
        save([C.name 'C.mat'], 'C')  
        disp(['saved file name ' C.name 'C.mat']);        
    end
    
end % file

disp('eyelink2_saccade_detect')